#include "../common/icsearch.hpp"
#include <gflags/gflags.h>

DEFINE_bool(run_mode, false, "程序的运行模式， false-调试； true-发布");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    ChatSystem::InitLogger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    std::vector<std::string> host_list = {"http://127.0.0.1:9200/"};
    std::shared_ptr<elasticlient::Client> client = std::make_shared<elasticlient::Client>(host_list);
    // std::shared_ptr<elasticlient::Client> client(new elasticlient::Client({"http://127.0.0.1:9200/"}));
    ChatSystem::ESIndex index(client, "test_user", "_doc");
    // index.append("昵称");
    // index.append("手机号", "keyword", "standard", true);
    // index.create();
    
    //由于append成员函数返回的是ESIndex对象本身，所以可以连续调用append
    int ret = index.append("昵称").append("手机号", "keyword", "standard", true).create();
    if(ret == true)
    {
        LOG_INFO("索引创建成功！");
    }

    //新增数据
    ChatSystem::ESInsert insert(client, "test_user", "_doc");
    ret = insert.append("昵称", "张三").append("手机号", "15570030424").insert("0001");
    if(ret == false)
    {
        LOG_ERROR("新增数据失败！");
    }
    ret = insert.append("昵称", "赵六").append("手机号", "15570030424").insert("0002");
    if(ret == false)
    {
        LOG_ERROR("新增数据失败！");
    }
    //只要数据的id相同，新增就是修改
    ret = insert.append("昵称", "王五").append("手机号", "15570030424").insert("0003");
    if(ret == false)
    {
        LOG_ERROR("数据更新失败！");
    }
    sleep(2);   //这里不加休眠会出现插入可能还没有完成，查询不到数据的问题；
    //查询数据
    ChatSystem::ESSearch search(client, "test_user", "_doc");
    Json::Value user = search
    .append_should_match("手机号.keyword", "15570030424")
    .append_must_not_terms("昵称.keyword", {"张三"})
    .search();
    if(user.empty() || user.isArray() == false)
    {
        LOG_ERROR("结果为空，或者结果不是数组类型!");
    }
    int sz = user.size();
    for(int i = 0; i < sz; ++i)
    {
        LOG_INFO("昵称：{}", user[i]["_source"]["昵称"].asString());
    }

    sleep(2);
    // 删除数据
    ChatSystem::ESRemove remove(client, "test_user", "_doc");
    remove.remove("0001");
    remove.remove("0002");
    remove.remove("0003");

    return 0;
}